home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11957 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.3 KB  |  59 lines

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Specifying Data Layout
  5. Date: Sun, 17 Mar 1996 07:35:15 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.0000006c.00028969@fred>
  8. References: <1996Mar14.173643.8651@nosc.mil>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client122.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <1996Mar14.173643.8651@nosc.mil>, sampson@cod.nosc.mil (Charles H. 
  14. Sampson) wrote:
  15. >      I've just finished reading the reference manual part of Stroustrup's
  16. > "The C++ Programming Language" (2nd ed) and have a number of questions. 
  17. > This one is particularly important to a project I'm working on.  A quick
  18. > search of the FAQ didn't turn up anything, nor does it seem to appear in
  19. > the 1400+ articles currently in the comp.lang.c++ newsgroup on my news
  20. > server.
  21. >      Is there some way of precisely specifying the memory layout of a
  22. > struct?  In other words, can you say, "This struct is to occupy 3 words of
  23. > memory, element foo is to occupy bits 5-12 of word 1, element fern is to
  24. > occupy ..."?  If it can be done with a struct, can it also be done with a
  25. > class (specifying locations for the data members only)?  In this case, can
  26. > you also control the gizmo that is used to distinguish the various values
  27. > of a class hierarchy, both where it is to be allocated and the values to be
  28. > used to identify specific members of the hierarchy?
  29. The way to do it is:
  30.  
  31. struct Packed
  32. {
  33.   unsigned short a:3; // 3 bits
  34.   unsigned short b:5; // 5 more bits
  35.   unsigned short c:8; // the remaining 8 bits for a 16 bits unsigned short
  36. };
  37.  
  38. The a, b, c member of the Packed struct will be stored in 2 bytes of memory.
  39.  
  40. BTW, the same syntax works for classes.
  41.  
  42. The exact layout of the bits is implementation dependant as:
  43.  - unsigned short isn't necessarily 16 bits long,
  44.  - the processor store most significant bytes first or last.
  45. So read compiler documentation and experiment to find out which exact layout 
  46. will work for you.
  47.  
  48. One reason you've found nothing in the C++ FAQ is that it is a C syntax that 
  49. C++ have inherited. As most C++ programmers learn C first, they already know 
  50. this trick.
  51.  
  52.  Frederic LACHASSE (ECP 86)
  53.  CompuServe: 100530,2005
  54.  Internet: lachass@worldnet.fr
  55.  
  56.